package DARCOShared.requests;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;

import DARCOShared.utils.SecurityUtilities;

public class RequestWrapper {
	public byte[] request;
	public byte[] encodedPassword;
	public byte[] encodedSalt;
	
	public RequestType requestType;

	public RequestWrapper(){}
	
	
	public RequestWrapper(RequestBase req) {
		requestType = req.getRequestType();
		
		String password = SecurityUtilities.getRandomString(16);
		byte[] salt = SecurityUtilities.getRandomString(20).getBytes();

		ByteArrayOutputStream b = new ByteArrayOutputStream();
		ObjectOutputStream o;
		try {
			o = new ObjectOutputStream(b);

			o.writeObject(req);
			request = SecurityUtilities.PBEEncrypt(salt, password, b.toByteArray());
			encodedPassword = SecurityUtilities.encode(SecurityUtilities.getServerPublicKey(), password.getBytes());
			encodedSalt = SecurityUtilities.encode(SecurityUtilities.getServerPublicKey(), salt);
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}

	public RequestBase getRequest(Key prvKey) {
		try {
			String decodedPassword = new String(SecurityUtilities.decode(prvKey, encodedPassword));
			byte[] decodedSalt = SecurityUtilities.decode(prvKey, encodedSalt);
						
			byte[] decodedRequest = SecurityUtilities.PBEDecrypt(decodedSalt, decodedPassword, request);
			ByteArrayInputStream b = new ByteArrayInputStream(decodedRequest);
			ObjectInputStream o = new ObjectInputStream(b);
			return((RequestBase)o.readObject());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
